import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '*',
    redirect: '/'
  },
  {
    path: '/',
    name: 'Home',
    component: () => import('@/views/Home'),
  },
  {
    path: '/goods',
    name: 'Goods',
    component: () => import('@/views/Goods')
  },
  {
    path: '/about',
    name: 'About',
    component: () => import('@/views/About')
  },
  {
    path: '/goods/details',
    name: 'Details',
    component: () => import('../views/Details.vue')
  },
  {
    path: '/shoppingCart',
    name: 'ShoppingCart',
    component: () => import('@/views/ShoppingCart')
  },
  {
    path: '/collect',
    name: 'Collect',
    component: () => import('../views/Collect.vue')
  },
  {
    path: '/order',
    name: 'Order',
    component: () => import('../views/Order.vue')
  },
]

// const router = new VueRouter({
//   mode: 'history',
//   base: process.env.BASE_URL,
//   routes
// })

//原因:在vue-router在3.1之后把 $router.push方法 改成了promise.如果没有错误捕获回调函数,错误信息就会交给全局路由进行错误处理.因此就会报错
//Uncaught (in promise) NavigationDuplicated: Avoided redundant navigation to current location: "/"
// 解决方案: 禁止全局路由错误处理打印, 这个也是vue-router的开发者给出的解决方案
const originalPush = VueRouter.prototype.push
//重写原有的VueRouter.prototype.push方法
VueRouter.prototype.push = function push(location) {
    //调用call方法的原因是为了始终保持this指向,之后在原有的push方法上增加一个catch捕获
    return originalPush.call(this, location).catch(err => err)
}

const router = new VueRouter({
    routes
})


import store from "../store/index"

//路由守卫
router.beforeEach((to,from,next)=>{
  if(to.meta.loginFlag && !store.getters.userInfo){
    //如果当前vuex中存在userInfo那么就表示用户登录了
    store.commit("setShowLogin", true)
    return next(false)
}
  next()
})

export default router
